//
//  ViewController.m
//  makepack_tools
//
//  Created by tangs on 2017/7/15.
//  Copyright © 2017年 tangs. All rights reserved.
//

#import "ViewController.h"

#import "MyButton.h"
#import "MyTextField.h"
#import "MyImageView.h"

@implementation FileSystemItem

static FileSystemItem   *s_rootItem   = nil;
static NSString         *s_configPath = nil;
static NSString         *s_title = nil;
//static NSMutableArray   *leafNode   = nil;

+ (void)initialize {
//    if (self == [FileSystemItem class]) {
//        leafNode = [[NSMutableArray alloc] init];
//    }
}

- (id)initWithPath:(NSString *)path {
    self = [super init];
    if (self) {
//        relativePath = [[path lastPathComponent] copy];
//        parent = parentItem;
        keyMap = [[NSMutableDictionary alloc] init];
        self->configPath = path;
    }
    return self;
}

+ (void)setConfigPath:(NSString*)path {
    s_rootItem = nil;
    s_configPath = path;
}

+ (FileSystemItem *)rootItem {
    if (s_rootItem == nil) {
        s_rootItem = [[FileSystemItem alloc] initWithPath:s_configPath];
    }
    return s_rootItem;
}

// Creates, caches, and returns the array of children
// Loads children incrementally
- (NSArray *)children {
    
    if (children == nil) {
        NSFileManager *fm = [NSFileManager defaultManager];
        NSData* data = [fm contentsAtPath:configPath];
        if (data == nil) {
            children = [[NSArray alloc] init];
        } else {
            NSString *result = [[NSString alloc] initWithData: data
                                                     encoding: NSUTF8StringEncoding];
            // 转换windows换行符
            result = [[result stringByReplacingOccurrencesOfString: @"\r\n" withString: @"\n"]
                      stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NSArray *items = [result componentsSeparatedByString: @"\n"];
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (NSString* str in items) {
                if ([str rangeOfString: @"#"].location != 0) {
//                    NSString* str1 = [@"," stringByAppendingString: str];
                    NSArray* lineItems = [str componentsSeparatedByString: @","];
                    NSMutableArray *array1 = [[NSMutableArray alloc] initWithArray:lineItems];
                    NSNumber *number = [[NSNumber alloc] initWithBool:NO];
                    [array1 insertObject:number atIndex:0];
                    [array addObject: array1];
                } else {
                    s_title = [[NSString alloc] initWithString:str];
                    NSArray *keys = [str componentsSeparatedByString: @","];
                    int i = 0;
                    for (NSString* str in keys) {
                        keyMap[str] = [NSString stringWithFormat: @"%d", i];
                        ++i;
                    }
                }
            }
            self->children = array;
        }
    }
    return children;
}

- (FileSystemItem *)childAtIndex:(NSUInteger)n {
    return [[self children] objectAtIndex:n];
}


- (NSInteger)numberOfChildren {
    NSArray *tmp = [self children];
//    return (tmp == leafNode) ? (-1) : [tmp count];
    return [tmp count];
}

@end

@implementation ViewController
- (IBAction)outlineView:(NSOutlineView *)sender {
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    
    tasks = [[NSMutableArray alloc] initWithCapacity:32];
    
    self.outlineView.delegate = self;
    self.outlineView.dataSource = self;
    [self.outlineView reloadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onSelectedFile:)
                                                 name:@"selectedConfigFile"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onStartMakeApks:)
                                                 name:@"startMakeApks"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onSelectAll:)
                                                 name:@"selectAll"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onUnselectAll:)
                                                 name:@"unselectAll"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(save:)
                                                 name:@"save"
                                               object:nil];
}

- (void)viewDidDisappear {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)update:(NSTimer *)timer {
    
}

- (void)onSelectedFile:(NSNotification *) noti {
    [FileSystemItem setConfigPath:noti.userInfo[@"path"]];
    [self.outlineView reloadData];
}

- (void)save:(NSNotification *) noti {
    if (s_title == nil) return;
    NSMutableString* text = [[NSMutableString alloc] initWithCapacity:1024 * 50];
    [text appendString:s_title];
    [text appendString:@"\n"];
    for (int i = 0; i < self.outlineView.numberOfRows; ++i) {
        NSArray *item = [self.outlineView itemAtRow:i];
        for (int j = 1; j < item.count; ++j) {
            if (j > 1) {
                [text appendString:@","];
            }
            [text appendString:item[j]];
        }
        [text appendString:@"\n"];
    }
    if (![text writeToFile:s_configPath atomically:YES encoding:NSUTF8StringEncoding error:nil]) {
        [self showAlert:@"提示" withText:@"保存配置文件失败."];
        NSLog(@"save fail");
    } else {
        [self showAlert:@"提示" withText:@"保存配置文件成功."];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"save_succ"
                                                            object:self
                                                          userInfo:nil];
    }
}

- (void)onStartMakeApks:(NSNotification *) noti {
    if ([tasks count] > 0) {
        [self showAlert:@"打包任务正在执行" withText:@"请在当前所有任务执行完毕后再开始新的任务."];
        return;
    }
    
    for (int i = 0; i < self.outlineView.numberOfRows; ++i) {
        NSTableCellView *view = [self.outlineView viewAtColumn:0 row:i makeIfNecessary:NO];
        if (view != nil) {
            NSButton *button =  view.subviews[0];
            if (button != nil && button.state == NSOnState) {
                NSArray *item = [self.outlineView itemAtRow:i];
//                NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(makeApk:) object:item];
//                [thread start];
//                [self makeApk:item];
                [tasks addObject:item];
            }
        }
    }
    if ([tasks count]) {
        [self makeApk:tasks[0]];
        [tasks removeObjectAtIndex:0];
    }
}

- (void)onSelectAll:(NSNotification *) noti {
    for (int i = 0; i < self.outlineView.numberOfRows; ++i) {
        NSTableCellView *view = [self.outlineView viewAtColumn:0 row:i makeIfNecessary:NO];
        if (view != nil) {
            NSButton *button =  view.subviews[0];
            if (button != nil) {
                button.state = NSOnState;
            }
        }
    }
}

- (void)onUnselectAll:(NSNotification *) noti {
    for (int i = 0; i < self.outlineView.numberOfRows; ++i) {
        NSTableCellView *view = [self.outlineView viewAtColumn:0 row:i makeIfNecessary:NO];
        if (view != nil) {
            NSButton *button =  view.subviews[0];
            if (button != nil) {
                button.state = NSOffState;
            }
        }
    }
}

- (void)showAlert:(NSString*)title withText:(NSString*)text {
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"OK"];
    [alert setMessageText:title];
    [alert setInformativeText:text];
    [alert setAlertStyle:NSAlertStyleWarning];
    [alert runModal];
}

- (void)addLogToView:(NSString*)text {
    NSDictionary* dic = @ {
        @"log" : text
    };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"add_log"
                                                        object:self
                                                      userInfo:dic];
}

- (void)makeApk:(NSArray*)item {
    NSString *path = [s_configPath stringByDeletingLastPathComponent];
    NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:16];
    [arguments addObjectsFromArray:@[@"make_apk_mac.py"]];
    [arguments addObjectsFromArray:item];
    [arguments removeObjectAtIndex:1];
    
    NSTask *task = [[NSTask alloc ]init];
    [task setLaunchPath:@"/usr/bin/python"];
    [task setArguments:arguments];
    [task setCurrentDirectoryPath:path];
    
    NSPipe *outputPipe = [NSPipe pipe];
    NSFileHandle *file = [outputPipe fileHandleForReading];
    [task setStandardOutput:outputPipe];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotification object:file];
    [file readToEndOfFileInBackgroundAndNotify];
    [task launch];
    NSString* log = @"###################开始打包任务###################";
    log = [log stringByAppendingString:@"\n*******渠道信息********\n"];
    for (NSString* str in item) {
        log = [log stringByAppendingFormat:@"%@\n", str];
    }
    log = [log stringByAppendingString:@"*******渠道信息********\n\n"];
    [self addLogToView:log];
}

- (void)readCompleted:(NSNotification *)notification {
    NSData *data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    NSLog(@"Read data: %@", string);
    [self addLogToView:string];
    [self addLogToView:@"#############################################\n"];
    NSRange range = [string rangeOfString:@"make apk end, succ!"];
    if (range.location == NSNotFound) {
        [tasks removeAllObjects];
        [self showAlert:@"失败" withText:@"打包失败."];
        return;
    }
    if ([tasks count]) {
        [self makeApk:tasks[0]];
        [tasks removeObjectAtIndex:0];
    } else {
        [self showAlert:@"成功" withText:@"所有打包任务完成."];
    }
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[notification object]];
}

- (NSInteger)outlineView:(NSOutlineView *)outlineView
  numberOfChildrenOfItem:(id)item {
    if (item == nil) item = [FileSystemItem rootItem];
    return [item numberOfChildren];
}

- (BOOL)outlineView:(NSOutlineView *)outlineView
   isItemExpandable:(id)item {
//    return (item == nil) ? YES : ([item numberOfChildren] != -1);
    return NO;
}


- (id)outlineView:(NSOutlineView *)outlineView
            child:(NSInteger)index ofItem:(id)item {
    if (item == nil) item = [FileSystemItem rootItem];
    return [(FileSystemItem *)item childAtIndex:index];
}

- (id)outlineView:(NSOutlineView *)outlineView
objectValueForTableColumn:(NSTableColumn *)tableColumn
           byItem:(id)item {
    id cell = [tableColumn dataCellForRow:0];
    return cell;
}

- (nullable NSView *)outlineView: (NSOutlineView *)outlineView
              viewForTableColumn: (nullable NSTableColumn *)tableColumn
                            item: (id)item {
    NSInteger idx = [outlineView.tableColumns indexOfObject:tableColumn];
    NSTableCellView *result = [outlineView makeViewWithIdentifier:tableColumn.identifier owner:self];
    if (idx > 1) {
        id destIdx = [tableColumn identifier];
        int index = [destIdx intValue] + 1;
        MyTextField* tf = result.subviews[0];
        [tf bindData:item withIndex:index];
        if (index < [item count]) {
            tf.stringValue = item[index];
        } else {
            tf.stringValue = @"";
        }
    } else if (idx == 1) {
        id view = result.subviews[0];
        [view bindData:item withConfigPath:s_configPath];
        [view update];
    } else if (idx == 0) {
        MyButton *button = result.subviews[0];
        [button bindData:item];
        if ([item[0] boolValue] == YES) {
            button.state = NSControlStateValueOn;
        } else {
            button.state = NSControlStateValueOff;
        }
    }
    return result;
}

- (IBAction)onNeedMakepackSwitched:(NSButtonCell *)sender {
    
}

- (nullable NSTableRowView *)outlineView:(NSOutlineView *)outlineView rowViewForItem:(id)item {
    return nil;
}

- (void)outlineView:(NSOutlineView *)outlineView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row {

}

- (void)outlineView:(NSOutlineView *)outlineView didRemoveRowView:(NSTableRowView *)rowView forRow:(NSInteger)row {
    
}


@end
